using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletPool : SingletonMono<BulletPool>
{
    public GameObject bulletPrefab;
    public int poolSize = 50; // 增加初始池大小
    
    private Queue<GameObject> bulletPool = new Queue<GameObject>();
    
    private void Start()
    {
        InitializePool();
    }
    
    void InitializePool()
    {
        for (int i = 0; i < poolSize; i++)
        {
            // GameObject bullet = ABMgr.GetInstance().LoadAssetBundleSync<GameObject>("model", "Bullet");
            GameObject bullet = ABMgr.GetInstance().LoadAssetBundleSync<GameObject>("model", "ShootBullet");
            // 设置子弹到独立碰撞层避免与玩家碰撞
            bullet.transform.SetParent(transform);
            int layerIndex = LayerMask.NameToLayer("Projectile");
            if (layerIndex == -1)
            {
                Debug.LogWarning("Projectile layer not found, using default layer 10");
                layerIndex = 10; // 使用第10层作为备用
            }
            bullet.layer = layerIndex;
            
            Debug.Log("子弹层设置为: " + bullet.layer, this);
            // 重要：请在Unity编辑器的Physics 2D设置中，确保Projectile层与Player层不发生碰撞
            // Edit > Project Settings > Physics 2D > Layer Collision Matrix
            if (bullet.GetComponent<BulletScript>() == null)
            {
                Debug.LogError("子弹预制体缺少BulletScript组件！", this);
            }
            bullet.SetActive(false);
            bulletPool.Enqueue(bullet);
        }
    }
    
    public GameObject GetBullet(Vector3 position)
    {
        if (bulletPool.Count == 0)
        {
            ExpandPool(10); // 增加每次扩展数量
        }
        
        GameObject bullet = bulletPool.Dequeue();
        bullet.transform.position = position;
        bullet.SetActive(true);
        return bullet;
    }
    
    //从池子中取出子弹，并将其返回到池子中，以便复用。
    public void ReturnBullet(GameObject bullet)
    {
        bullet.SetActive(false);
        bullet.transform.position = Vector3.zero;
        bullet.GetComponent<TrailRenderer>().Clear();//Trail Renderer拖尾重置
        bulletPool.Enqueue(bullet);
    }
    
    void ExpandPool(int amount)
    {
        for (int i = 0; i < amount; i++)
        {
            GameObject bullet = ABMgr.GetInstance().LoadAssetBundleSync<GameObject>("model", "Bullet");
            bullet.transform.SetParent(transform);
            bullet.SetActive(false);
            bulletPool.Enqueue(bullet);
        }
    }
}
